package com.hlx.service.impl;

import com.hlx.mapper.ChatPdfMapper;
import com.hlx.service.ChatPdfService;
import com.hlx.utils.AliyunOSSOperator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.MalformedURLException;

@Slf4j
@RequiredArgsConstructor
@Service
public class ChatPdfServiceImpl implements ChatPdfService {
	private final ChatPdfMapper chatPdfMapper;
	private final AliyunOSSOperator aliyunOSSOperator;

	/**
	 * 保存PDF资源
	 * @param file
	 * @return
	 */
	@Override
	public String save(MultipartFile file) {
		String url;
		try {
			url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
		} catch (Exception e) {
			log.error("Failed to save PDF resource.", e);
			return null;
		}
		if (url == null || url.isEmpty()){
			return null;
		}
		// 保存映射关系
		String chatId = String.valueOf(System.currentTimeMillis());
		chatPdfMapper.save(chatId, url);
		return chatId;
	}

	/**
	 * 获取PDF资源
	 * @param chatId
	 * @return
	 */
	@Override
	public Resource getFile(String chatId) {
		String pdfUrl = chatPdfMapper.getFile(chatId);
		try {
			// 使用UrlResource处理网络URL
			return new UrlResource(pdfUrl);
		} catch (MalformedURLException e) {
			// 处理URL格式错误（如无效的URL）
			throw new RuntimeException("无效的文件URL: " + pdfUrl, e);
		}
	}
}
